package com.fangyu.lottery.mq;

import com.fangyu.lottery.model.PrizeDistributionMessage;
import com.fangyu.lottery.service.PrizeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author fangyu
 * @version v1.0.0
 * @since 2025/8/27 23:44
 */
@Slf4j
@Component
public class PrizeDistributionConsumer {

    @Autowired
    private PrizeService prizeService;

    @RabbitListener(queues = "prize.distribution.queue")
    public void handleDistribution(PrizeDistributionMessage message) {
        try {
            // 根据奖品类型调用不同的发放服务
            switch (message.getPrizeType()) {
                case "COUPON":
                    prizeService.distributeCoupon(message.getUserId(), message.getPrizeId());
                    break;
                case "POINT":
                    prizeService.distributePoints(message.getUserId(), message.getPrizeId());
                    break;
                case "PHYSICAL":
                    prizeService.distributePhysicalPrize(message.getUserId(), message.getPrizeId());
                    break;
                default:
                    log.warn("未知的奖品类型: {}", message.getPrizeType());
            }

            // 记录发放日志
            prizeService.recordDistributionLog(message);

        } catch (Exception e) {
            // 记录失败，可用于重试或人工处理
            log.error("奖品发放失败: {}", message, e);
            throw new AmqpRejectAndDontRequeueException(e);
        }
    }
}